package cn.com.generaldata.os.ws.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hwpf.HWPFDocument;
import org.nutz.ioc.annotation.InjectName;
import org.nutz.lang.Files;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.com.generaldata.os.service.impl.IndicatorWordService;

@Component
@InjectName
public class IndicatorWordWS {

	private static final Logger logger = LoggerFactory.getLogger(IndicatorWordWS.class);

	@Autowired
	private IndicatorWordService reportIndicatorQueryService;

	/**
	 * 跳转到导出word报表.
	 */
	@At("/report/toExportWordReport")
	@Ok("jsp:/static/ocean/report/exportWordReport")
	public void toExport(HttpServletRequest req) {

	}

	/**
	 * 导出word报表.
	 * 
	 * @throws IOException
	 */
	@At("/report/doExportWordReport")
	@Ok("void")
	public void doExport(@Param("timeType") int timeType, @Param("year") int year, @Param("quarter") int quarter,
			@Param("month") int month, @Param("numPoint") int numPoint, @Param("persentPoint") int persentPoint,
			HttpServletResponse response, HttpServletRequest request, ServletContext context) throws IOException {

		// 模板路径
		String folderPath = context.getRealPath("/WEB-INF/") + File.separator + "classes" + File.separator
				+ "exportWordTemplateFolder" + File.separator;

		// 生成word文件
		HWPFDocument doc = reportIndicatorQueryService.exportWordReport(timeType, year, quarter, month, folderPath,
				numPoint, persentPoint);
		if (doc == null) {
			// 出错
		}

		// 模板文件名
		String fileName = reportIndicatorQueryService.getWordTemplateFileName(timeType);

		// 设置输出的格式
		response.setContentType("application/octet-stream");
		response.addHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, "utf-8")
				+ "\";filename*=utf-8''" + URLEncoder.encode(fileName, "utf-8"));
		doc.write(response.getOutputStream());
	}

	/**
	 * 下载word模板.
	 * 
	 * @param fileName
	 *            文件名
	 * @param response
	 * @param context
	 * @throws UnsupportedEncodingException
	 */
	@At("/report/downloadExportWordTemplate")
	@Ok("void")
	public void downloadLocal(@Param("timeType") int timeType, HttpServletResponse response,
			HttpServletRequest request, ServletContext context) throws UnsupportedEncodingException {

		// 模板路径
		String folderPath = context.getRealPath("/WEB-INF/") + File.separator + "classes" + File.separator
				+ "exportWordTemplateFolder" + File.separator;

		// 模板文件名
		String fileName = reportIndicatorQueryService.getWordTemplateFileName(timeType);

		// 读到流中
		InputStream inStream = null;
		try {
			inStream = new FileInputStream(folderPath + fileName);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		// 设置输出的格式
		response.setContentType("application/octet-stream");
		response.addHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, "utf-8")
				+ "\";filename*=utf-8''" + URLEncoder.encode(fileName, "utf-8"));

		// 循环取出流中的数据
		byte[] b = new byte[64 * 1024];
		int len;
		try {
			while ((len = inStream.read(b)) > 0) {
				response.getOutputStream().write(b, 0, len);
				response.getOutputStream().flush();
			}
			inStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 上传模板文件.
	 * 
	 */
	@At("/report/uploadExportWordTemplate")
	@POST
	@AdaptBy(type = UploadAdaptor.class)
	@Ok("jsp:/static/ocean/report/exportWordReport")
	public void saveFile(@Param("uploadFile") TempFile uploadFile, ServletContext context, HttpServletRequest request) {

		// 检查
		if (uploadFile == null || uploadFile.getFile().length() < 10) {
			request.setAttribute("message", "请上传正确的模板文件。");
			return;
		}

		// 后缀名
		String ext = uploadFile.getMeta().getFileExtension();
		if (!".doc".equals(ext)) {
			request.setAttribute("message", "请上传正确的模板文件。");
			return;
		}

		// 模板路径
		String folderPath = context.getRealPath("/WEB-INF/") + File.separator + "classes" + File.separator
				+ "exportWordTemplateFolder" + File.separator;

		// 移动文件
		boolean isOK = false;
		try {

			//原文件名
			String localName = uploadFile.getMeta().getFileLocalName();

			//忽略浏览器自动添加的数字部分，如"渔业经济形势分析模板（年报） (5).doc"，认为是"渔业经济形势分析模板（年报）.doc"
			int iIndex = localName.indexOf("(");
			if (iIndex != -1) {
				localName = localName.substring(0, iIndex).trim() + ".doc";
			}

			// 删除旧文件
			File targetFile = new File(folderPath + localName);
			if (targetFile.exists()) {
				isOK = Files.deleteFile(targetFile);
				if (!isOK) {
					request.setAttribute("message", "模板文件上传失败，删除旧文件失败。");
					return;
				}
			}

			// 复制过去
			isOK = Files.move(uploadFile.getFile(), targetFile);
			if (isOK) {
				request.setAttribute("message", "模板文件上传成功。");
			} else {
				request.setAttribute("message", "模板文件上传失败。");
			}
		} catch (IOException e) {
			request.setAttribute("message", "模板文件上传失败。" + e.getMessage());
		}

	}
}
